<template>
    <div class="edit-task">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>编辑任务</span>
        </div>
        <el-form :model="taskForm" label-width="100px">
          <el-form-item label="任务名称">
            <el-input v-model="taskForm.name"></el-input>
          </el-form-item>
          <el-form-item label="完成状态">
            <el-switch v-model="taskForm.status"></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveTask">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        taskForm: {
          id: null,
          name: '',
          status: false
        }
      };
    },
    created() {
      this.initializeTask();
    },
    methods: {
      initializeTask() {
        const taskId = this.$route.query.taskId;
        console.log(taskId)
        if (taskId) {
          this.fetchTask(taskId);
        }
      },
      fetchTask(taskId) {
        const token = localStorage.getItem('token');
        axios.get(`/api/tasks/${taskId}`, {
          headers: {
            'Authorization': token
          }
        })
            .then(response => {
              this.taskForm = response.data;  // 假设响应数据直接是任务对象
            })
            .catch(error => {
              this.$message.error('加载任务信息失败');
            });
      },
      saveTask(taskId) {
        const token = localStorage.getItem('token');
        this.taskForm.id = this.$route.query.taskId;
        axios.post(`/api/tasks/save`, this.taskForm, {
          headers: {
            'Authorization': token
          }
          // params: { taskId: taskId }
        })
            .then(() => {
              this.$message.success('任务已修改');
              this.$router.push('/todolist'); // 假设你有一个路由用于添加任务
            })
            .catch(error => {
              this.$message.error('加载任务信息失败');
            });
      },
      cancel() {
        this.$router.go(-1); // 返回上一页
      }
    }
  };
  </script>
  
  <style scoped>
  .edit-task {
    margin: 20px;
  }
  .box-card {
    width: 400px;
  }
  </style>